package com.example.kiratest.realize;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

/**
 * 模拟python的
 */
@RestController
@SpringBootApplication
public class PlayStoreCrawler {

    private static final Logger logger = LoggerFactory.getLogger(PlayStoreCrawler.class);

    // 使用HTTP客户端替代Python库
    private final CloseableHttpClient httpClient;

    public PlayStoreCrawler() {
        this.httpClient = HttpClients.custom()
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();
    }

    @GetMapping("/getVersion")
    public ResponseEntity<?> getAppVersion(
            @RequestParam String packageName,
            @RequestParam(defaultValue = "en") String lang,
            @RequestParam(defaultValue = "us") String country) {

        if (packageName == null || packageName.isEmpty()) {
            return ResponseEntity.badRequest().body(
                    Map.of("error", "Package name is required"));
        }

        try {
            String version = fetchFromPlayStore(packageName, lang, country);
            return ResponseEntity.ok(version);
        } catch (Exception e) {
            logger.error("Failed to fetch version for {}", packageName, e);
            return ResponseEntity.internalServerError().body(
                    Map.of("error", e.getMessage()));
        }
    }

    private String fetchFromPlayStore(String packageName, String lang, String country) throws IOException {
        // 模拟Google Play请求（需根据实际反爬策略调整）
        HttpGet request = new HttpGet(
                "https://play.google.com/store/apps/details?id=" + packageName + 
                "&hl=" + lang + "&gl=" + country);
        
        // 设置真实浏览器Header
        request.setHeader("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            String html = EntityUtils.toString(response.getEntity());
            return parseVersionFromHtml(html); // 解析HTML获取版本
        }
    }

    // 使用Jsoup解析HTML
    private String parseVersionFromHtml(String html) {
        Document doc = Jsoup.parse(html);
        Element versionElement = doc.selectFirst("div[itemprop=softwareVersion]");
        return versionElement != null ? versionElement.text() : "Unknown";
    }

    public static void main(String[] args) {
        SpringApplication.run(PlayStoreCrawler.class, args);
    }
}